package com.starsea.book.ui.newpage

import android.os.Bundle
import android.view.View
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.starsea.book.R
import com.starsea.book.base.VMBaseFragment
import com.starsea.book.databinding.ActivityReadHistoryBinding
import com.starsea.book.ui.newpage.adapter.MsgListAdapter
import com.starsea.book.ui.newpage.viewmodel.MsgViewModel
import com.starsea.book.utils.gone
import com.starsea.book.utils.toastOnUi
import com.starsea.book.utils.viewbindingdelegate.viewBinding
import com.starsea.book.utils.visible

/**
 * @author Lee
 * @createTime 2023-12-26 09 GMT+8
 * @desc :
 */
class MsyFragment() : VMBaseFragment<MsgViewModel>(R.layout.activity_read_history) {

    private val binding by viewBinding(ActivityReadHistoryBinding::bind)
    override val viewModel by viewModels<MsgViewModel>()

    var newsType = 0

    var name = ""

    var page = 1

    lateinit var mAdapter: MsgListAdapter

    companion object {
        fun newInstance(newsType: Int, name: String): MsyFragment {
            val args = Bundle()
            val fragment = MsyFragment()
            args.putInt("newsType", newsType)
            args.putString("name", name)
            fragment.arguments = args
            return fragment
        }
    }


    override fun onFragmentCreated(view: View, savedInstanceState: Bundle?) {
        newsType = requireArguments().getInt("newsType")
        name = requireArguments().getString("name", "")

        binding.titleBarView.gone()
        binding.tvEmptyMsg.text = "暂无消息"

        mAdapter = MsgListAdapter(requireContext()) {

        }
        binding.rvContent.layoutManager = LinearLayoutManager(requireContext())
        binding.rvContent.adapter = mAdapter

        viewModel.getMsgList(newsType, page)
        viewModel.readAll()

        binding.refreshLayout.setOnRefreshListener {
            page = 1
            viewModel.getMsgList(newsType, page)
        }
        binding.refreshLayout.setOnLoadMoreListener {
            page++
            viewModel.getMsgList(newsType, page)
        }

        viewModel.msgListResult.observe(this) {
            if (it.status == 200) {

                if (page == 1) {
                    binding.refreshLayout.finishRefresh()
                    mAdapter.setItems(it.data!!.list)
                } else {
                    binding.refreshLayout.finishLoadMore()
                    mAdapter.addItems(it.data!!.list ?: arrayListOf())
                }

                if (it.data!!.list.size < 10) {
                    binding.refreshLayout.finishLoadMoreWithNoMoreData()
                }

                binding.tvEmptyMsg.visible(mAdapter.isEmpty())

            } else if (it.status == 401) {
                toastOnUi("登录过期,请重新登录")
                LoginActivity.start(requireContext())
            } else {
                toastOnUi(it.msg)
            }
        }

    }

}